package com.fillter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class character
 */
@WebFilter("/charcater")
public class charcater implements Filter {

    /**
     * Default constructor. 
     */
    public charcater() {
        // TODO Auto-generated constructor stub
    }

    private String encoding;   
    // ��Ŀ����ʱ���Ѿ���������    
    public void destroy() {    
        //System.out.println("end do the encoding filter!");4
        encoding="UTF-8";    
    } 
    
    public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {    
        System.out.println("before encoding " + encoding + " filter��");    
        req.setCharacterEncoding(encoding);
        resp.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset="+encoding);
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //String str = response.getOutputStream().toString();
       // System.out.println("***"+xxx(response.getOutputStream()));
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);
        HttpSession s = request.getSession();
        String flag = (String)s.getAttribute("flag");       
        if(flag!=null){
        	chain.doFilter(req, resp); 
        }
        else {
        	String url = request.getRequestURL().toString();
        	int index = url.lastIndexOf("login.html");
        	int index2 = url.lastIndexOf("login.do");
        	if(index>0 || index2>0) chain.doFilter(req, resp);
        	else response.getWriter().print("<script>window.location.href = 'login.html'</script>");
        	System.err.println("----------------------------------------"+index);
        }
    }    
     
   
    
    // ��Ŀ����ʱ���Ѿ����ж�ȡ    
    public void init(FilterConfig config) throws ServletException {    
    	this.encoding = config.getInitParameter("encoding");
    }    

}

